# -*- coding: utf-8 -*-
import os
from Qt.QtCore import *
from liberLibs import utils
from liberLibs.library import Library
import liberConfig
reload(liberConfig)


def exists():
    config_file = liberConfig.PATH_SETTINGS_FILE
    return True if os.path.isfile(config_file) else False


def read():
    """
    read config file
    :return:
    """
    config_file = liberConfig.PATH_SETTINGS_FILE
    libs = Library().all_libs()
    if not os.path.isfile(config_file):
        origin_data = dict()
        for lib in libs:
            origin_data[lib] = {"is_current": False,
                                "paths": {"all": [], "current": ""}}
        write(origin_data)
    else:
        origin_data = utils.read_json(config_file)
        has_new_library = False
        for lib in libs:
            if lib not in origin_data:
                origin_data[lib] = {"is_current": False,
                                    "paths": {"all": [], "current": ""}}
                has_new_library = True
        if has_new_library:
            write(origin_data)
    return origin_data


def write(data):
    """
    write history data
    :param data: a dict
    :return:
    """
    config_file = liberConfig.PATH_SETTINGS_FILE
    utils.write_json(config_file, data)


def clear(library):
    history_data = read()
    library_data = history_data.get(library)
    library_data["paths"]["all"] = []
    library_data["paths"]["current"] = ""
    write(history_data)


def update(library, is_current, current_path):
    """
    :param library: str
    :param is_current: bool
    :param current_path: str
    :return:
    """
    history_data = read()
    for lib_key in history_data:
        history_data[lib_key]["is_current"] = False
    library_data = history_data.get(library)
    library_data["is_current"] = is_current
    library_data["paths"]["current"] = current_path
    write(history_data)


def append(library, path):
    """
    :param library: a library name
    :param path: str
    :return:
    """
    path = path.replace("\\", "/")
    history_data = read()
    origin_paths = history_data.get(library).get("paths").get("all")
    if path in origin_paths:
        return
    origin_paths.insert(0, path)
    history_data[library]["paths"]["all"] = origin_paths
    write(history_data)


if __name__ == "__main__":
    pass
